package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.BankCardParams;
import com.baidu.ocr.sdk.model.BankCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.fengba.nanzhi.fengba.MainActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class CardActivity extends Activity {

    private static final int REQUEST_CODE_GENERAL = 105;
    private static final int REQUEST_CODE_BANKCARD = 111;



    private TabHost tabHost;//声明TabHost组件的对象
    private RecyclerView mCardyhk;
    private RecyclerView mCardcxk;
    private JSONArray jsonArray1;
    private JSONArray jsonArray2;
    private ImageButton Cardfh;
    private AlertDialog.Builder alertDialog;
    private Button addcard1,addcard2;
    private String user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wz_activity_card);
        alertDialog = new AlertDialog.Builder(this);
        getUser_id();
        Token();
        init();
        init2();

        //addcxk = findViewById(R.id.addcard2);



        Cardfh =  findViewById(R.id.cardfh);

        Cardfh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tabHost=(TabHost)findViewById(android.R.id.tabhost);//获取tabHost对象
        tabHost.setup();//初始化TabHost组件

        LayoutInflater inflater=LayoutInflater.from(this);//声明并实例化一个LayoutInflater对象
        //关于LayoutInflater详细，请看我的另外一篇转载的总结
        inflater.inflate(R.layout.wz_activity_card1, tabHost.getTabContentView());
        inflater.inflate(R.layout.wz_activity_card2, tabHost.getTabContentView());

        tabHost.addTab(tabHost.newTabSpec("tab01")
                .setIndicator("信用卡")
                .setContent(R.id.linearLayout1));//添加第一个标签页
        tabHost.addTab(tabHost.newTabSpec("tab02")
                .setIndicator("储蓄卡")
                .setContent(R.id.linearLayout2));//添加第二个标签页
        updateTab(tabHost);
        tabHost.setOnTabChangedListener(new tabChangedListener());




        //信用卡
        addcard1 = findViewById(R.id.addcard1);
        addcard1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(CardActivity.this,AddCardActivity.class);
                    intent.putExtra("cardtype","2");
                    startActivity(intent);
                }
            });
        //储蓄卡
        addcard2 = findViewById(R.id.addcard2);
        addcard2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CardActivity.this,AddCardActivity.class);
                intent.putExtra("cardtype","1");
                startActivity(intent);
            }
        });

//        addcxk.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(CardActivity.this,AddCardActivity.class);
//                startActivity(intent);
//            }
//        });
//        tabHost.getTabWidget().getChildTabViewAt(0).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mBtnaddcard2.setVisibility(View.GONE);
//                mBtnaddcard2.setVisibility(View.VISIBLE);
//            }
//        });
//        tabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mBtnaddcard1.setVisibility(View.GONE);
//                mBtnaddcard2.setVisibility(View.VISIBLE);
//            }
//        });
    }

    private void updateTab(final TabHost tabHost)
    {
        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++)
        {
            View view = tabHost.getTabWidget().getChildAt(i);
            TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);

           // tv.setTextColor(Color.rgb(255, 255, 255));
          //  TextView tv = tabHost.getTabWidget().getChildAt(i).findViewById(R.id.cardtab);
            if (tabHost.getCurrentTab() == i)
            {
                tv.setTextSize(14);
                tv.setTypeface(Typeface.SERIF, 0);
                //选中
                view.setBackground(getResources().getDrawable(R.drawable.card_xz));//选中后的背景
                tv.setTextColor(this.getResources().getColorStateList(R.color.colorcheng));
            }
            else
            {
                tv.setTextSize(12);
                tv.setTypeface(Typeface.SERIF, 0);
                //不选中
                view.setBackground(getResources().getDrawable(R.drawable.card_wxz));//非选择的背景.
                tv.setTextColor(this.getResources().getColorStateList(android.R.color.black));

            }
        }

        final RefreshLayout refreshLayout1 = (RefreshLayout)findViewById(R.id.yhklbLayout);

        refreshLayout1.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        if(jsonArray1==null) {
                            Toast.makeText(CardActivity.this, "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayout1.finishRefresh();
                        }else{
                            Toast.makeText(CardActivity.this, "查询成功", Toast.LENGTH_SHORT).show();
                            refreshLayout1.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout1.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

        final RefreshLayout refreshLayout2 = (RefreshLayout)findViewById(R.id.cxklbLayout);

        refreshLayout2.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init2();
                        if(jsonArray1==null) {
                            Toast.makeText(CardActivity.this, "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayout2.finishRefresh();
                        }else{
                            Toast.makeText(CardActivity.this, "查询成功", Toast.LENGTH_SHORT).show();
                            refreshLayout2.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout2.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

    }
    /**
     * TabHost选择监听器
     * @author
     *
     */
    private class tabChangedListener implements TabHost.OnTabChangeListener {

        @Override
        public void onTabChanged(String tabId)
        {
            tabHost.setCurrentTabByTag(tabId);
            updateTab(tabHost);
        }
    }

    public void init() {
        OKManager.getInstance().type1024(user_id, "1", new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if (jsonObject.get("code").equals(0)) {
                        jsonArray1 = jsonObject.getJSONArray("data");

                        mCardyhk = findViewById(R.id.cardxyktab);
                        mCardyhk.setLayoutManager(new LinearLayoutManager(CardActivity.this));
                        mCardyhk.setAdapter(new Card1Adapter(CardActivity.this,jsonArray1));
                    } else {
                        showToast(CardActivity.this,jsonObject.get("message").toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                showToast(CardActivity.this,"网络错误");
            }
        });
    }

    public void init2() {

        OKManager.getInstance().type1024(user_id, "2", new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                //ToastUtil.showToast(PostParameterActivity.this, "Code：" + String.valueOf(response.code()));
                try {
                    if (jsonObject.get("code").equals(0)) {
                        jsonArray2 = jsonObject.getJSONArray("data");

                        mCardcxk = findViewById(R.id.cardcxktab);
                        mCardcxk.setLayoutManager(new LinearLayoutManager(CardActivity.this));
                        mCardcxk.setAdapter(new Card2Adapter(CardActivity.this,jsonArray2));
                    } else {
                        showToast(CardActivity.this,jsonObject.get("message").toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                showToast(CardActivity.this,"网络错误");
            }
        });

    }



    public void getUser_id(){
        Object user_info = Preferences.getParam(CardActivity.this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());

            //账号
            user_id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void Token(){
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
             //   showToast(CardActivity.this,token+"成功！！！！！！！！");
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
              //  showToast(CardActivity.this,error+"失败！！！！！！！！！");
                showToast(CardActivity.this,"网络错误");
            }
        }, getApplicationContext(), "7outqMHRUg9Fjsd3RFs0PZNG", "AIbOlma4wGOchToB6bfUs3Ac41GpB6Wh");
    }

    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}